/* Copyright (c) 2022 渝州大数据实验室
 *
 * Lanius is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *
 *     http://license.coscl.org.cn/MulanPSL2
 *
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 */
package org.yzbdl.lanius.orchestrate.serv.service.system.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.yzbdl.lanius.orchestrate.serv.dto.system.OrgParamDto;
import org.yzbdl.lanius.orchestrate.serv.dto.system.OrgQueryDto;
import org.yzbdl.lanius.orchestrate.serv.entity.system.OrgEntity;
import org.yzbdl.lanius.orchestrate.serv.entity.system.UserOrgEntity;
import org.yzbdl.lanius.orchestrate.serv.mapper.system.OrgMapper;
import org.yzbdl.lanius.orchestrate.serv.mapper.system.UserOrgMapper;
import org.yzbdl.lanius.orchestrate.serv.service.system.OrgService;
import org.yzbdl.lanius.orchestrate.serv.utils.CurrentUserUtil;
import org.yzbdl.lanius.orchestrate.common.base.entity.IdFieldEntity;
import org.yzbdl.lanius.orchestrate.common.exception.runtime.BusinessException;
import org.yzbdl.lanius.orchestrate.common.utils.MessageUtil;

import java.util.List;

/**
 * 组织服务
 *
 * @author chenjunhao@yzbdl.ac.cn
 * @date 2022-04-08 13:31
 */
@Service
public class OrgServiceImpl extends ServiceImpl<OrgMapper, OrgEntity> implements OrgService {


	@Autowired
	UserOrgMapper userOrgMapper;

	/**
	 * 根据用户id查询组织
	 * @param userId 用户id
	 * @return 组织列表
	 */
	@Override
	public List<OrgEntity> queryOrgByUserId(Long userId){
		return baseMapper.queryOrgByUserId(userId);
	}

	/**
	 * 根据分页查询组织
	 * @param orgQueryDto 查询条件
	 * @param page 分页对象
	 * @return 组织分页列表
	 */
	@Override
	public Page<OrgEntity> listOrgPage(OrgQueryDto orgQueryDto, Page<OrgEntity> page){
		return baseMapper.selectPage(page, new LambdaQueryWrapper<OrgEntity>()
			.like(OrgEntity::getOrgName,orgQueryDto.getOrgName()).orderByDesc(OrgEntity::getCreateTime)
		);
	}

	/**
	 * 根据组织名称查询组织
	 * @param orgName 组织名称
	 * @return 组织列表
	 */
	@Override
	public List<OrgEntity> listOrgByOrgName(String orgName){
		QueryWrapper<OrgEntity> queryWrapper = new QueryWrapper<>();
		if(StringUtils.isNoneEmpty(orgName)){
			queryWrapper.lambda().like(OrgEntity::getOrgName,orgName);
		}
		return baseMapper.selectList(queryWrapper);
	}

	/**
	 * 查看当前用户是否属于某组织
	 * @param orgId 组织id
	 * @return 是否
	 */
	@Override
	public boolean isCurrentUserBelongToOrg(Long orgId){
		return userOrgMapper.exists(
				new LambdaQueryWrapper<UserOrgEntity>()
						.eq(UserOrgEntity::getOrgId,orgId)
						.eq(UserOrgEntity::getUserId, CurrentUserUtil.getCurrentUserId())
		);
	}

	/**
	 * 查看当前用户是否属于某组织
	 * @param orgId 组织id
	 * @return 是否
	 */
	@Override
	public boolean isUserInOrg(Long userId,Long orgId){
		return userOrgMapper.exists(
				new LambdaQueryWrapper<UserOrgEntity>()
						.eq(UserOrgEntity::getOrgId,orgId)
						.eq(UserOrgEntity::getUserId, userId)
		);
	}

	/**
	 * 改变组织冻结状态
	 * @param frozen 冻结状态值
	 * @param orgId 组织id
	 * @return 是否
	 */
	@Override
	public boolean changeOrgFrozen(Boolean frozen, Long orgId){
		return update(new LambdaUpdateWrapper<OrgEntity>()
			.eq(IdFieldEntity::getId,orgId).set(OrgEntity::getFrozen,frozen)
				.last("limit 1")
		);
	}

	/**
	 * 将用户添加进新的组织中
	 * @param userId 用户id
	 * @param orgId 组织id
	 * @param chief 是否是领袖
	 * @return 更改行数
	 */
	@Override
	public int addUserIntoOrg(Long userId,Long orgId,boolean chief){
		return userOrgMapper.insert(UserOrgEntity.builder()
				.userId(userId)
				.orgId(orgId)
				.orgChief(chief)
				.build()
		);
	}

	/**
	 * 添加组织并关联已有用户
	 * @param orgParamDto 组织参数
	 * @return 更改行数
	 */
	@Override
	public int insertOrgRelateUser(OrgParamDto orgParamDto){
		OrgEntity orgEntity = OrgEntity.builder().orgName(orgParamDto.getOrgName()).frozen(false).build();
		save(orgEntity);
		return addUserIntoOrg(orgParamDto.getUserId(),orgEntity.getId(),true);
	}

	/**
	 * 检测是否存在组织
	 * @param orgName 组织名称
	 * @return 布尔值
	 */
	@Override
	public boolean existOrg(String orgName){
		LambdaQueryWrapper<OrgEntity> queryWrapper = new LambdaQueryWrapper<>();
		queryWrapper.eq(OrgEntity::getOrgName,orgName);
		return baseMapper.exists(queryWrapper);
	}

	/**
	 * 更新组织
	 * @param orgEntity 组织实体
	 * @return 布尔值
	 */
	@Override
	public boolean updateOrg(OrgEntity orgEntity){
		LambdaQueryWrapper<OrgEntity> queryWrapper = new LambdaQueryWrapper<>();
		queryWrapper.eq(OrgEntity::getOrgName,orgEntity.getOrgName()).ne(IdFieldEntity::getId,orgEntity.getOrgName());
		if(baseMapper.exists(queryWrapper)){
			throw new BusinessException(MessageUtil.get("system.org.same_org_name"));
		}
		return updateById(orgEntity);
	}

//	private boolean insertOrg(String orgName){
//		LambdaQueryWrapper<OrgEntity> queryWrapper = new LambdaQueryWrapper<>();
//		queryWrapper.eq(OrgEntity::getOrgName,orgName);
//		if(!baseMapper.exists(queryWrapper)){
//			OrgEntity orgEntity = OrgEntity.builder().orgName(orgName).frozen(false).build();
//			return save(orgEntity);
//		}
//		throw new BusinessException(MessageUtil.get("system.org.same_org_name"));
//	}

}
